import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'

const state = {
  token: getToken(),
  userInfo: {},
  routers: constantRoutes
}

const mutations = {
  setToken(state, token) {
    // 将token值保存到vuex中
    state.token = token
    // 将token值保存到本地存储中
    setToken(token)
  },
  removeToken(state) {
    // 清除vuex中的token
    state.token = null
    // 清除本地存储中的token
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRouters(state, newRouters) {
    state.routers = [...constantRoutes, ...newRouters]
  }
}

const actions = {
  async login(context, payload) {
    const res = await login(payload)
    context.commit('setToken', res)
  },
  async getUserInfo(context) {
    const res = await getUserInfo()
    context.commit('setUserInfo', res)
    return res
  },
  logout(context) {
    context.commit('removeToken')
    // 清除用户信息
    context.commit('setUserInfo', {})
    resetRouter() // 重置路由
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
